package com.robot.member.controller;

import com.alibaba.fastjson.JSON;
import com.robot.member.client.MerchantClient;
import com.robot.member.client.OrdersClient;
import com.robot.member.pojo.Evaluate;
import com.robot.member.pojo.Member;
import com.robot.member.pojo.client.Orders;
import com.robot.member.pojo.client.Store;
import com.robot.member.service.EvaluateService;
import com.robot.member.service.MemberService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * evaluate控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/evaluate")
public class EvaluateController {
    @Autowired
    private EvaluateService evaluateService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * orders表status=0-未支付 1-已支付 2-关闭订单
     */
    private String ordersStatusPaid = "1";

    /**
     * orders表evaluating是否评价 0-未评价 1-已评价
     */
    private String ordersEvaluating = "0";

    /**
     * 店铺store表status=0-禁用 1-启用
     */
    private String storeStatusEnable = "1";


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, evaluateService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "admin/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.SUCCESS_QUERY, evaluateService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Evaluate> pageList = evaluateService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<Evaluate>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, evaluateService.findSearch(searchMap));
    }

    /**
     * 发表评价
     *
     * @param storeId
     * @param evaluate
     * @return
     */
    @PostMapping("{storeId}")
    public Result add(@PathVariable String storeId, @RequestBody Evaluate evaluate) {
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断
        Member member=memberService.findByClaims(request);

        if (evaluate.getContent() == null || "".equals(evaluate.getContent())) {
            return new Result(StatusCode.ERROR_CONTENT_REQUIRED);
        }

        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(storeId), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null || !storeStatusEnable.equals(storeInDb.getStatus())) {
            return new Result(StatusCode.ERROR, "该店铺不存在或者异常,暂无法使用");
        }

        Orders orders = JSON.parseObject(ordersClient.thirdFindOrderByOrdersId(evaluate.getOrdersId()), Orders.class);

        logger.info("subOrdersInDb=" + orders);
        if (orders == null) {
            return new Result(StatusCode.ERROR, "订单不存在");
        }
        if (!ordersStatusPaid.equals(orders.getStatus())) {
            return new Result(StatusCode.ERROR, "订单不是已支付状态");
        }
        //这里可能需要补刀

        evaluateService.add(evaluate,orders);
        ordersClient.thirdUpdateOrders(orders);
        return new Result(StatusCode.SUCCESS_COMMENT);
    }

    /**
     * 修改
     *
     * @param evaluate
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody Evaluate evaluate, @PathVariable String id) {
        evaluate.setId(id);
        evaluateService.update(evaluate);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        evaluateService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 根据merchantId查商家下所有评价并分页
     *
     * @param merchantId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("findEvaluatesByMerchantId/{merchantId}/{page}/{size}")
    public PageResult<Evaluate> findAllByCompanyIdOrderByCreatedAtDesc(@PathVariable String merchantId, @PathVariable int page, @PathVariable int size) {
        Page<Evaluate> pageData = evaluateService.findAllByCompanyIdAndDeletedAtIsNullOrderByCreatedAtDesc(merchantId, page, size);
        PageResult<Evaluate> pageResult = new PageResult<>(pageData.getTotalElements(), pageData.getContent());
        return pageResult;
    }


    /**
     * 根据memberID查找会员名下所有评价并分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{page}/{size}")
    public Result findEvaluatesByMemberId(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Page<Evaluate> pageData = evaluateService.findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 根据id和memberID查找会员名下某一评价
     *
     * @param id
     * @return
     */
    @GetMapping("findEvaluateById/{id}")
    public Result findEvaluateByIdAndMemberId(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Evaluate evaluateInDb = evaluateService.findByIdAndMemberId(id, claims.getId());
        logger.info("evaluateInDb=" + evaluateInDb);
        if (evaluateInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, evaluateInDb);
    }

    /**
     * 根据ordersId和memberID查找会员名下某一评价
     *
     * @param ordersId
     * @return
     */
    @GetMapping("findEvaluateByOrdersId/{ordersId}")
    public Result findEvaluateByOrdersIdAndMemberId(@PathVariable String ordersId) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Evaluate evaluateInDb = evaluateService.findByOrdersIdAndMemberId(ordersId, claims.getId());
        logger.info("evaluateInDb=" + evaluateInDb);
        if (evaluateInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, evaluateInDb);
    }
}
